<?php
/**
 * 上传单图
 * @author yupoxiong<i@yufuping.com>
 */

namespace generate\field;

class Image extends Field
{
    public static $html = <<<EOF
   
    <div class="layui-form-item">
    <label for="avatar" class="layui-form-label [REQUIRED]">[FORM_NAME]</label>
    <div class="layui-input-inline">
        <div class="layui-upload-drag" id="[FIELD_NAME]">
            <i class="layui-icon"></i>
            <p>点击上传，或将文件拖拽到此处</p>
        </div>
        <div class="layui_img">
            <div class="layui-progress thumb_progress" id="[FIELD_NAME]_progress"
                lay-showPercent="yes" lay-filter="progressBar[FIELD_NAME]">
                <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
            </div>
            <img src="{\$data.[FIELD_NAME]|default='[FIELD_DEFAULT]'}" {if !isset(\$data.[FIELD_NAME]) || \$data.[FIELD_NAME] == ''} style='display: none;'  {/if} id="srcimg[FIELD_NAME]" alt=""
                class="srcimgavatar" srcset="">
            <input type="hidden" name="[FIELD_NAME]" lay-verify="[FORM_VALIDATE]" id="inputimg[FIELD_NAME]"
                value="{\$data.[FIELD_NAME]|default='[FIELD_DEFAULT]'}">
        </div>
    </div>
    </div>
    <script>
    layui.use('upload', function () {
        var upload = layui.upload;
        upload.render({
            elem: '#[FIELD_NAME]'
            , url: "{:url('upfile/upload')}"
            , acceptMime: 'image/*'
            , accept: 'images'
            , size: 1024
            , progress: function (n, elem, res, index) {
                $('#[FIELD_NAME]_progress').show();
                var percent = n + '%'
                element.progress('progressBar[FIELD_NAME]', percent);
            }
            , done: function (res, index, upload) {
                if (res.code == 1) {
                $("#inputimg[FIELD_NAME]").val(res.data.url);
                $('#[FIELD_NAME]_progress').hide();
                $("#srcimg[FIELD_NAME]").attr('src', res.data.url).show();
            } else {
                layer.msg(res.msg, { icon: 2, time: 2000 });
                element.progress('progressBar[FIELD_NAME]', '0%');
                $('#[FIELD_NAME]_progress').hide();
            }

            }
        });
    })
</script>
    \n
EOF;

    public static $rules = [
        'required'   => '非空',
        'file_size'  => '文件大小限制',
        'file_image' => '图片类型',
        'regular'    => '自定义正则'
    ];


    public static function create($data)
    {
        $html = self::$html;
        $html = str_replace(['[FORM_NAME]','[FIELD_NAME]', '[FORM_VALIDATE]', '[REQUIRED]','[FIELD_DEFAULT]'], [$data['form_name'], $data['field_name'], self::$verify, self::$required, $data['field_default']], $html);
        return $html;
    }
}